package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpRequest {
    private Socket socket;
    private Map<String, String> headers = new HashMap<>();
    private String method;
    private String uri;
    private String protocol;


    public HttpRequest(Socket socket) throws IOException {
        this.socket = socket;
        parseRequestLine();
        parseHeaders();
    }

    public void parseRequestLine() throws IOException {
        String line = readLine();
        System.out.println(line);

        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];

        System.out.println("method:" + method);
        System.out.println("uri:" + uri);
        System.out.println("protocol:" + protocol);
    }

    public void parseHeaders() throws IOException {
        while (true) {
            String line = readLine();
            if (line.isEmpty()) {
                break;
            }
            System.out.println("消息头：" + line);
            String[] data = line.split(":\\s");
            headers.put(data[0], data[1]);
        }
        System.out.println("headers:" + headers);
    }

    public void parseContent(){}

    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();
        char pre = 'a', cru = 'a';
        while ((d = in.read()) != -1) {
            cru = (char) d;
            if (pre == 13 && cru == 10) {
                break;
            }
            builder.append(cru);
            pre = cru;
        }
        return builder.toString().trim();

    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeaders(String name) {
        return headers.get(name);
    }
}
